const loading = $("loading");
const invalid = $("invalid");
const error = $("error");

function $(id) {
  return document.getElementById(id);
}

function show(id) {
  $(id).style.display = "block";
}

function hide(id) {
  $(id).style.display = "none";
}

var contentURL,
  screenshot = {};
chrome.tabs.query({ active: true, lastFocusedWindow: true }, function (tabs) {
  const activeTab = tabs[0];
  contentURL = activeTab.url;

  // 网址是否匹配可以截取图片
  if (isUrlMatches(contentURL)) {
    let loaded = false;
    // 需要滚动网页内容,这里以编程的方式直接运行content.js文件
    chrome.scripting.executeScript(
      {
        target: { tabId: activeTab.id },
        files: ["content.js"],
      },
      function () {
        // todos
        loaded = true;
        show("loading");
        // 通过消息传递通知content.js
        chrome.tabs.sendMessage(
          activeTab.id,
          { msg: "scrollPage" },
          function () {
            console.log("发送消息之后....");
          }
        );
      }
    );

    window.setTimeout(() => {
      if (!loaded) {
        show("error");
      }
    }, 1000);
  } else {
    // 网址不匹配
    show("invalid");
  }
});

const matches = ["http://*/*", "https://*/*", "file://*/*", "ftp://*/*"];
const noMatches = [/^https?:\/\/www.baidu.com\/.*$/];

function isUrlMatches(url) {
  for (let i = 0; i < noMatches.length; i++) {
    if (noMatches[i].test(url)) {
      return false;
    }
  }

  let r;
  for (let i = 0; i < matches.length; i++) {
    r = new RegExp("^" + matches[i].replace(/\*/g, ".*") + "$");
    if (r.test(url)) {
      return true;
    }
  }

  return false;
}

chrome.runtime.onMessage.addListener(async function (
  request,
  sender,
  sendResponse
) {
  if (request.msg === "capturePage") {
    await capturePage(request, sender, sendResponse);
  } else if (request.msg === "capturePageComplete") {
    // 打开预览页面
    openPreview();
  }
});

async function capturePage(request, sender, sendResponse) {
  return new Promise((resolve, reject) => {

    // 屏幕实际像素和css像素存在差距
    // 在高分辨率之下，1个css像素可能对应多个屏幕像素

    let scale = request.devicePixelRatio && request.devicePixelRatio !== 1 ? 1 / request.devicePixelRatio : 1;

    if (scale !== 1) { 
      request.x = request.x / scale;
      request.y = request.y / scale;
      request.totalWidth = request.totalWidth / scale;
      request.totalHeight = request.totalHeight / scale;
    }


    if (!screenshot.canvas) {
      screenshot.canvas = document.createElement("canvas");
      screenshot.ctx = screenshot.canvas.getContext("2d");
      screenshot.canvas.width = request.totalWidth;
      screenshot.canvas.height = request.totalHeight;
    }

    chrome.tabs.captureVisibleTab(function (dataUrl) {
      if (dataUrl) {
        let image = new Image();
        image.onload = function () {
          screenshot.ctx.drawImage(image, request.x, request.y);
          chrome.tabs.query(
            { active: true, lastFocusedWindow: true },
            function (tabs) {
              let tab = tabs[0];
              chrome.tabs.sendMessage(
                tab.id,
                { msg: "scrollPage" },
                function () {
                  console.log("发送消息之后....");
                }
              );
              resolve();
            }
          );
        };
        image.src = dataUrl;
      }
    });
  });
}

// 生成随机字符串
function getRandomString(length = 16) {
  return Math.random()
    .toString(36)
    .substring(2, length + 2);
}

function openPreview() {
  const dataURL = screenshot.canvas.toDataURL();
  const name = "capture-web-" + getRandomString();

  chrome.storage.local.remove(["captureImg"], function () {
    console.log("删除成功");
  });

  chrome.storage.local.set({ 'captureImg': dataURL, 'name': name }, function () {
    chrome.tabs.create(
      { url: chrome.runtime.getURL("preview/preview.html") },
      function (tab) {
        console.log("预览页面打开成功");
      }
    );
  });
}
